const express = require("express");
const app = express();
const joi = require("joi");
// toke模块引入
const jwt = require("./jwt");
const multer = require("multer")
const uuid = require("uuid")
const {pool} = require("./pool")

// cors跨域
var cors = require("cors"); //先引入cors中间件
app.use(cors({ //添加允许跨域的客户端地址
  origin: ["http://localhost:8080", "http://101.35.142.7:80", "http://101.35.142.7"],
  credentials: true  //允许客户端发送cookie到服务器
}))



// 拦截特定请求进行token验证
app.use((req, res, next) => {
  // 测试期间 白名单为登录  实际为注册
  if (req.url != '/user/ulogin' && req.url != '/user/ureg' && req.url != '/user/getcode' && req.url != '/user/uppwd' &&
    (req.url.startsWith("/user") ||
      req.url.startsWith("/upload")
    )) {
    let token = req.headers.token;
    let result = jwt.verifyToken(token);
    // 如果考验通过就next，否则就返回登陆信息不正确
    if (result === undefined) {
      res.send({ status: 403, msg: "未提供证书" })
    } else if (result.name == 'TokenExpiredError') {
      res.send({ status: 403, msg: '登录超时，请重新登录' });
    } else if (result.name == "JsonWebTokenError") {
      res.send({ status: 403, msg: '证书出错' })
    } else {
      req.user = result;
      next();
    }
  } else {
    next();
  }
});
// 用户图片接口
app.get('/public/image/avatar/*', (req, res) => {
  res.sendFile(__dirname + '/' + req.url);
})
// 商品图片接口
app.get('/public/image/family/*', (req, res) => {
  res.sendFile(__dirname + '/' + req.url);
})
// 用户图片上传
// 用户头像上传配置
let uploadOptions = multer.diskStorage({
  //指定目录
  destination: (req, file, cd) => {
    cd(null, "public/image/avatar/")
  },
  filename: (req, file, cd) => {
    let name = file.originalname
    let ext = name.substr(name.lastIndexOf("."))
    cd(null, uuid.v4() + ext)
  }
})
// 导入
const uploadTools = multer({
  storage: uploadOptions,
  limits: {
    fileSize: 2 * 1024 * 1024,
    fieldsize: 2 * 1024 * 1024,
    fields: 1  //防止doss攻击，每次都只允许上传一个文件
  }
})

// 用户头像上传接口
app.post("/upload", uploadTools.array("uploadFile"), (req, res) => {
  let { uid } = req.user;
  if (req.files.length > 0) {

    let filename = req.files[0].filename
    pool.query("update lj_user set avatar=? where lj_user.uid=?", [`${filename}`, uid], (err, result) => {
      if (result.affectedRows > 0) {
        // 上传成功
        var sql1 = "select * from lj_user where uid=?"
        pool.query(sql1, uid, (err, result) => {
          res.send({
            ok: 1,
            msg: "头像上传成功",
            token: jwt.generateToken(result[0])
          })
        })
      }
      console.log(`用户${uid}在${new Date().getHours() + ":" + new Date().getMinutes()}时间上传了头像,插入数据库${result.affectedRows ? '成功' : '失败'}了`)
    })
  }
})
//引入路由地址
const userRouter = require("./router/user.js");  //用户
const adiminRouter = require("./router/admin");  //管理员

const Joi = require("joi");


//解析post中间件
app.use(express.urlencoded({
  extended: false
}));


// 为所有用户路由前缀v1
app.use("/user", userRouter)    //用户
app.use("/admin", adiminRouter)    //用户



//对错误格式进行错误处理
app.use((err, req, res, next) => {
  // 捕获验证数据中间件错误
  if (err instanceof joi.ValidationError) {
    return res.send({
      error: err,
      msg: "错误的提交格式"
    })
  }
  // 捕获上传中间件错误
  if (err instanceof multer.MulterError) {
    return res.send({
      ok: -100,
      msg: "文件过大!或者其他错误",
      error: err
    })
  }
  if (err) throw err
})


app.listen("4981", () => {
  console.log(`启动成功 端口号:4981`);
})